<?php

class UsersController extends GxController {

    public function filters() {
        return array('rights');
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id, 'Users'),
        ));
    }

    public function actionnewsLetter(){
        $this->layout=false;
        $userLists=  Users::model()->findAll('issubscribe='.SkillConfig::STATUS_ACTIVE);
       $usersData='<table>';
      
        foreach ($userLists as $userList){
            $usersData.='<tr><td>'.$userList->username.'</td></tr>';
        }
       $this->render('newsletter', array(
            'usersData' => $usersData,
        ));
    }

    

    public function actionviewClassCourse($id) {      
        $classModel = new CActiveDataProvider('Classes', array(
                    'criteria' => array(
                        'condition' => 'users_id=' . $id,
                    ),
                    'pagination' => array(
                        'pageSize' => 8,
                    ),
                ));
        $courseModel = new CActiveDataProvider('Courses', array(
                    'criteria' => array(
                        'condition' => 'users_id=' . $id,
                    ),
                    'pagination' => array(
                        'pageSize' => 8,
                    ),
                ));

        $this->render('_viewClassCourse', array(
            'classModel' => $classModel, 'courseModel' => $courseModel, 'model' => $this->loadModel($id, 'Users'),
        ));
    }

    public function actionCreate() {
        $model = new Users;
        $modelUserProfile = new Profiles;
        if (isset($_POST['Users'])) {
            $this->saveUserProfile($model, $modelUserProfile, 'create');
        }

        $this->render('create', array('model' => $model, 'modelUserProfile' => $modelUserProfile));
    }

    public function saveUserProfile($model, $modelUserProfile, $operation) {
        $uploadeDir = getUploadDir();
        if ($operation == "create") {
            /* For new record entry */
            if (isset($_POST['Profiles'])) {
                $db_logo = $modelUserProfile->photo;
                $model->setAttributes($_POST['Users']);
                $modelUserProfile->setAttributes($_POST['Profiles'], false);
                $modelUserProfile->setAttribute('photo', $db_logo);
                $modelUserProfile->setAttribute('termcondition', $_POST['Profiles']['termcondition']);

                $this->performAjaxValidation(array($model, $modelUserProfile));
                $validate = $modelUserProfile->validate();
                $validate = $model->validate() && $validate;
                $model->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                $model->createtime = time();
                if ($validate) {
                    if ($model->isNewRecord) {
                        $model->password = md5($model->password);
                        $model->is_users = SkillConfig::STATUS_ACTIVE;
                    }
                    $transaction = Yii::app()->getDb()->beginTransaction();
                    try {
                        if ($model->save(false)) {
                            $modelUserProfile->user_id = $model->id;

                            if (!empty($_FILES['Profiles']['name']['photo'])) {
                                $uploadeDir = getUploadDir() . $modelUserProfile->user_id;
                                if (!is_dir($uploadeDir)) {
                                    makeUploadDirCreateUsers('', $modelUserProfile->user_id);
                                }
                                $modelUserProfile->photo = CUploadedFile::getInstance($modelUserProfile, 'photo');
                                $fileInfo = pathinfo($modelUserProfile->photo);
                                $ext = $fileInfo['extension'];
                                $image = $_FILES['Profiles']['tmp_name'];
                                $mainTempImages = $image['photo'];
                                $rfilename = guid() . "." . strtolower($ext);
                                $uploadnewDirProfile = $uploadeDir . '/profile/' . $rfilename;
                                $uploadnewDirProfileThumb = $uploadeDir . '/profile/thumb/' . $rfilename;
                                $uploadnewDirProfileMiniThumb = $uploadeDir . '/profile/minithumb/' . $rfilename;
                                $uploadnewDirProfileMain = $uploadeDir . '/profile/432X324/' . $rfilename;
                                $modelUserProfile->photo->saveAs($uploadnewDirProfile);
                                $image = Yii::app()->image->load($uploadnewDirProfile);
                                $image->resize(USER_IMAGE_WIDTH, USER_IMAGE_HEIGHT, Image::NONE);
                                $image->save($uploadnewDirProfileThumb);
                                $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                                $imageThumb->resize(USER_IMAGE_THUMB_WIDTH, USER_IMAGE_THUMB_HEIGHT, Image::NONE);
                                $imageThumb->save($uploadnewDirProfileMiniThumb);

                                $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                                $imageThumb->resize(USER_IMAGE_PROFILE_WIDTH, USER_IMAGE_PROFILE_HEIGHT, Image::NONE);
                                $imageThumb->save($uploadnewDirProfileMain);
                                $modelUserProfile->photo = $rfilename;
                                $modelUserProfile->setAttribute('photo', $modelUserProfile->photo);
                                $modelUserProfile->setAttribute('user_id', $model->id);
                            }
                            $save = $modelUserProfile->save();
                        }
                        $transaction->commit();
                        if ($save) {

                            if (Yii::app()->getRequest()->getIsAjaxRequest())
                                Yii::app()->end();
                            else
                                $this->redirect(array('users/view/' . $model->id));
                        }
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                }
            }
        } else {
            /* For update existing record */
            if (isset($_POST['Profiles'])) {
                $db_logo = $modelUserProfile->photo;
                $model->setAttributes($_POST['Users'], false);
                $modelUserProfile->setAttributes($_POST['Profiles'], false);
                $modelUserProfile->setAttribute('termcondition', $_POST['Profiles']['termcondition']);
                $model->setAttribute('photo', $db_logo);
                $this->performAjaxValidation(array($model, $modelUserProfile)); //pr(array($model->user, $model));
                $validate = $modelUserProfile->validate();
                $validate = $model->validate() && $validate;
                $model->setAttribute('status', SkillConfig::STATUS_ACTIVE);

                if ($validate) {
                    $transaction = Yii::app()->getDb()->beginTransaction();
                    try {
                        if ($model->save(false)) {
                            $userProfile = $modelUserProfile->findByAttributes(array('user_id' => $model->id));
                            $modelUserProfile->user_id = $model->id;

                            if (!empty($_FILES['Profiles']['name']['photo'])) {
                                $uploadeDir = getUploadDir() . $modelUserProfile->user_id;
                                if (!is_dir($uploadeDir)) {
                                    makeUploadDirCreateUsers('', $modelUserProfile->user_id);
                                }
                                $modelUserProfile->photo = CUploadedFile::getInstance($modelUserProfile, 'photo');
                                $fileInfo = pathinfo($modelUserProfile->photo);
                                $ext = $fileInfo['extension'];
                                $image = $_FILES['Profiles']['tmp_name'];
                                $mainTempImages = $image['photo'];
                                $rfilename = guid() . "." . strtolower($ext);
                                $uploadnewDirProfile = $uploadeDir . '/profile/' . $rfilename;
                                $uploadnewDirProfileThumb = $uploadeDir . '/profile/thumb/' . $rfilename;
                                $uploadnewDirProfileMiniThumb = $uploadeDir . '/profile/minithumb/' . $rfilename;
                                $uploadnewDirProfileMain = $uploadeDir . '/profile/432X324/' . $rfilename;
                                $modelUserProfile->photo->saveAs($uploadnewDirProfile);
                                $image = Yii::app()->image->load($uploadnewDirProfile);
                                $image->resize(USER_IMAGE_WIDTH, USER_IMAGE_HEIGHT, Image::NONE);
                                $image->save($uploadnewDirProfileThumb);
                                $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                                $imageThumb->resize(USER_IMAGE_THUMB_WIDTH, USER_IMAGE_THUMB_HEIGHT, Image::NONE);
                                $imageThumb->save($uploadnewDirProfileMiniThumb);

                                $imageThumb = Yii::app()->image->load($uploadnewDirProfile);
                                $imageThumb->resize(USER_IMAGE_PROFILE_WIDTH, USER_IMAGE_PROFILE_HEIGHT, Image::NONE);
                                $imageThumb->save($uploadnewDirProfileMain);
                                $modelUserProfile->photo = $rfilename;
                                $modelUserProfile->setAttribute('photo', $modelUserProfile->photo);
                                $modelUserProfile->setAttribute('user_id', $model->id);
                            } else {

                                $modelUserProfile->photo = $userProfile->photo;
                            }

                            $save = $modelUserProfile->save();
                        }
                        $transaction->commit();
                        if ($save) {

                            if (Yii::app()->getRequest()->getIsAjaxRequest())
                                Yii::app()->end();
                            else
                                $this->redirect(array('users/view/' . $model->id));
                        }
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                }
            }
        }
    }

    public function actionUpdate($id) {
        $model = $this->loadModel($id, 'Users');
        $modelUserProfiles = Profiles::model()->find('user_id=:user_id', array(':user_id' => $id));
        $modelUserProfile = $this->loadModel($modelUserProfiles->profile_id, 'Profiles');
        $this->performAjaxValidation($model, 'users-form');
        if (isset($_POST['Users'])) {

            $this->saveUserProfile($model, $modelUserProfile, 'update');
        }
        $this->render('update', array(
            'model' => $model,
            'modelUserProfile' => $modelUserProfile,
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            $this->loadModel($id, 'Users')->delete();

            if (!Yii::app()->getRequest()->getIsAjaxRequest())
                $this->redirect(array('admin'));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionChangePassword() {
        $userId = $_POST['user_id'];
        $password = md5($_POST['password']);
        Users::model()->updateByPk($userId, array('password' => $password));
        Yii::app()->user->setFlash('success', Yii::t("msg", "Your password change successfully!"));

        exit();
    }

    public function actionAdmin() {
        $model = new Users('search');
        $model->unsetAttributes();
        $model->is_users = '1';
        $statusChangeUrl = Yii::app()->createUrl('Users/statuschange/');

        if (isset($_GET['Users']))
            $model->setAttributes($_GET['Users']);

        $this->render('admin', array(
            'model' => $model,
            'statusChangeUrl' => $statusChangeUrl,
        ));
    }

    public function actionStatuschange() {
        Users::model()->updateByPk($_POST['id'], array('status' => $_POST['status']));
    }

    public function actionsendmail() {
        $className = '';
        $courseName = '';
        $password = guid();
        Users::model()->updateByPk($_POST['id'], array('password' => $password));
        $classname = Classes::model()->findAllByAttributes(array('users_id' => $_POST['id']));
        $coursename = Courses::model()->findAllByAttributes(array('users_id' => $_POST['id']));

        if (!empty($classname)) {
            foreach ($classname as $value) {
                $className.='<li>' . $value->class_titile . '</lI>';
            }
        }
        if (!empty($coursename)) {
            foreach ($coursename as $value) {
                $courseName.='<li>' . $value->course_titile . '</lI>';
            }
        }
        $classCourseName = '<ul>' . $className . ' ' . $courseName . '</ul>';
        $userdetails = Users::model()->findByPk($_POST['id']);
        $mailmodel = EmailTemplate::model()->findByPk(Message::SEND_DETAILS_TO_USER);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $mailto = $userdetails->username;
        $arrayFind = array('[username]', '[password]', '[classcoursename]');
        $arrayReplace = array($mailto, $password, $classCourseName,);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;

        $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        //echo $body;die;
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
            echo SkillConfig::STATUS_ACTIVE;
        } catch (Exception $e) {
            echo $e;
            exit;
        }
    }

}